import API from "@/api";
import { md5 } from "js-md5";

interface SentenceEvaluatingInfo {
  sentence: string;
  isPhoneme?: boolean; // true：音素分析
}

interface OptionEvaluatingInfo {
  options: string[];
}

interface EvaluatingInfo {
  evaluatingInfo?: SentenceEvaluatingInfo | OptionEvaluatingInfo;
  audioBuffer: ArrayBuffer;
  onSuccess: (result: AnyObject) => void;
  onError: (errorMsg: string) => void;
}

interface IChivoxAuth {
  sig: string;
  appkey: string;
  timestamp: number;
}

export async function startEvaluating(data: EvaluatingInfo) {
  const result = await API.getChivoxAuth({}) as IChivoxAuth;

  var sig = result.sig;
  var timestamp = result.timestamp;
  var appkey = result.appkey;

  uni.connectSocket({
    url: "wss://cloud.chivox.com/ws?e=0&t=0&version=2",
  });

  uni.onSocketOpen(() => {
    console.log("连接已建立");
    startAuthentication();
    startEvaluating(evaluatingParams(data));
    sendAudioBlob(data.audioBuffer);
  });

  uni.onSocketError((error) => {
    console.error("发生错误:", error.errMsg);
    data.onError(error.errMsg);
  });

  uni.onSocketMessage((message) => {
    console.log("收到消息：", message);
    /** 这里要处理异常返回 */
    let obj = JSON.parse(message.data);
    data.onSuccess(obj);
    uni.closeSocket();
  });

  uni.onSocketClose((res) => {
    console.log("连接已关闭" + res);
  });

  function startAuthentication() {
    let authenticationInfo = {} as any;
    let app = {} as any;

    app["applicationId"] = appkey;
    app["sig"] = sig;
    app["alg"] = "md5";
    app["timestamp"] = timestamp.toString();
    app["userId"] = "000000";
    authenticationInfo["app"] = app;
    uni.sendSocketMessage({ data: JSON.stringify(authenticationInfo) });
  }

  function evaluatingParams(data: EvaluatingInfo) {
    let requestMap = {} as any;

    if (data.evaluatingInfo && "sentence" in data.evaluatingInfo) {
      if (data.evaluatingInfo.isPhoneme === true) {
        requestMap["coreType"] = "en.sent.score";
      } else {
        requestMap["coreType"] = "en.sent.pron";
      }

      requestMap["rank"] = 100;
      requestMap["refText"] = data.evaluatingInfo.sentence;
      requestMap["attachAudioUrl"] = 1;

      let resultMap = {} as any;
      let detailMap = {} as any;
      detailMap["phone"] = 1;
      resultMap["details"] = detailMap;
      requestMap["result"] = resultMap;
    } else if (data.evaluatingInfo && "options" in data.evaluatingInfo) {
      requestMap["coreType"] = "en.choc.score";
      requestMap["rank"] = 100;
      requestMap["precision"] = 1;
      requestMap["attachAudioUrl"] = 1;

      let refTextMap = {} as any;
      let lmArray = [] as any;
      data.evaluatingInfo.options.forEach((option) => {
        lmArray.push({ text: option, answer: 1 });
      });
      refTextMap["least_hit_cnt"] = 1;
      refTextMap["lm"] = lmArray;
      requestMap["refText"] = refTextMap;
    } else {
      requestMap["coreType"] = "en.asr.rec";
      requestMap["res"] = "en.asr.G4";

      requestMap["rank"] = 100;
      requestMap["attachAudioUrl"] = 1;

      let resultMap = {} as any;
      let detailMap = {} as any;
      detailMap["phone"] = 1;
      resultMap["details"] = detailMap;
      requestMap["result"] = resultMap;
    }

    return requestMap;
  }

  function startEvaluating(requestMap: any) {
    let evaluateInfo = {} as any;
    evaluateInfo["tokenId"] = Date.now().toString();
    evaluateInfo["request"] = requestMap;
    evaluateInfo["audio"] = { audioType: "wav", channel: 1, sampleBytes: 2, sampleRate: 16000 };
    uni.sendSocketMessage({ data: JSON.stringify(evaluateInfo) });
  }

  function sendAudioBlob(audioBuffer: ArrayBuffer) {
    console.log("发送音频");
    let emptyBuffer = new ArrayBuffer(0);
    uni.sendSocketMessage({ data: audioBuffer });
    uni.sendSocketMessage({ data: '{"cmd":"stop"}' });
  }
}
